package com.han.verifycode;


import com.han.verifycode.data.Answer;
import com.han.verifycode.data.RightKey;
import com.han.verifycode.enums.VerifyCodeEnum;

/**
 * 入口工具类
 */
public class VerifyCodeUtil {
    /**
     * 生成
     *
     * @param type
     * @param config
     */
    private static RightKey generateCode(VerifyCodeEnum type, CodeConfig config) {
        VerifyCodeEnum getType = VerifyCodeEnum.getByConfType(config);
        if (type != getType) {
            throw new RuntimeException("配置类型错误,需要类型为 " + type + "的配置");
        }
        VerifyCode instance = VerifyCodeEnum.getVerifyInstance(type);
        if (instance == null) {
            throw new RuntimeException("获取验证码实例失败");
        }
        return instance.generate(config);
    }

    /**
     * 只需提供配置就可以识别
     *
     * @param config
     * @return
     */
    public static RightKey generateCode(CodeConfig config) {
        return generateCode(VerifyCodeEnum.getByConfType(config), config);
    }


    /**
     * 验证
     * 结合配置 answer
     *
     * @return
     */
    public static boolean verify(RightKey rightKey, Answer answer) {
        VerifyCodeEnum type = VerifyCodeEnum.getByConfType(rightKey.getConfig());
        Class<? extends VerifyCode> vtype = type.getType();
        try {
            VerifyCode v = vtype.newInstance();
            return v.verify(rightKey, answer);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}
